package com.example.controller;

import com.example.domain.AddressBook;
import com.example.service.IAddressBookService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private IAddressBookService addressBookService;
    //查询外卖地址信息
    @GetMapping("/list")
    public R list(HttpSession session){
        //获取当前用户的id
        Long userId = (Long) session.getAttribute("user");
        //根据当前登录用户id查询所队应的地址信息
        List<AddressBook> list = addressBookService.list(userId);
        return new R(1,list);
    }
    //设置默认地址
    @PutMapping("/default")
    public R fault(@RequestBody AddressBook addressBook,HttpSession httpSession){
        Long user = (Long) httpSession.getAttribute("user");
        addressBookService.IsDefault(addressBook,user);
        return new R(1,"修改成功");
    }
    //添加地址信息
    @PostMapping
    public R save(@RequestBody AddressBook addressBook,HttpSession session){
        Long user = (Long) session.getAttribute("user");
        addressBookService.save(addressBook,user);
        return new R(1,"添加成功");
    }
    //回显修改地址信息
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id,HttpSession session){
        AddressBook addressBook = addressBookService.getById(id, (Long) session.getAttribute("user"));
        return new R(1,addressBook);
    }
    //修改地址信息
    @PutMapping
    public R update(@RequestBody AddressBook addressBook){
        addressBookService.update(addressBook);
        return new R(1,"修改成功");
    }
    //删除地址信息
    @DeleteMapping
    public R delete(Long ids,HttpSession session){
        addressBookService.delete(ids,(Long)session.getAttribute("user"));
        return new R(1,"删除成功");
    }
    @GetMapping("/default")
    public R defalt(HttpSession session){
        Long user = (Long) session.getAttribute("user");
        AddressBook defalt = addressBookService.defalt(user);
        return new R(1,defalt);
    }
}
